package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

/*	常用方法

	【18】Count:计数
	【19】GROUP：进行分组
	【20】Having:分组后进行过滤

*/

func main() {
	db, err := gorm.Open("mysql", "root:123456@tcp(192.168.11.189:3306)/lztest?charset=utf8&parseTime=True&loc=Local")

	if err != nil {
		panic(err)
	}
	defer db.Close()

	db.LogMode(true) //开启打印日志

	/*//创建两张表
	db.CreateTable(&User{})
	db.CreateTable(&UserInfo{})
	*/

	/* //向表中插入数据
	userinfo := UserInfo{

		Add:  "北京顺义",
		Desc: "我向说我很牛",
		User: User{
			UName: "张强",
			UAge:  22,
		},
	}

	db.Create(&userinfo)
	*/

	/*	//之前的关联表查询
		var userinfo UserInfo
		db.Preload("User").Find(&userinfo, "info_id = ?", 1)
		fmt.Println(userinfo)*/

	var userinfo UserInfo
	var getdate GetData
	db.Select("users.u_name ,users.u_age ,user_infos.add ,user_infos.desc").Joins("left join users on user_infos.usid = users.uid ").Find(&userinfo).Where("user_infos.usid = ?", 1).Scan(&getdate)
	fmt.Println(getdate)

}

type GetData struct {
	UName string
	UAge  int
	Add   string
	Desc  string
}

type User struct {
	UId   int `gorm:"primary_key;AUTO_INCREMENT"`
	UName string
	UAge  int
}

type UserInfo struct {
	InfoID int `gorm:"primary_key;AUTO_INCREMENT"`
	Add    string
	Desc   string
	User   User `gorm:"ForeignKey:Usid;AssociationForeignKey:UId"`
	Usid   int
}
